<?php
namespace plugins\goods\controller;
use app\common\lib\model_operate\Transit; //引入此类
use cmf\controller\PluginAdminBaseController;
use plugins\goods\model\GoodsAuditModel;
use plugins\goods\model\GoodsModel;
use plugins\store\Common;
use think\Db;
use think\Request;
/**
 * 需求配置首页
 */
class AdminIndexController extends PluginAdminBaseController
{
    protected $model;
    //页数
    protected $pagesize = 10;
    /**
     * 初始化
     */
    protected function _initialize()
    {
        $this->AM = new GoodsAuditModel;
        $this->model = new GoodsModel();
    }
    /**
     * 商品首页
     */
    public function index()
    {
        $data = $this->request->param();
        //分页
        $pagesize           = !empty($data['pagesize']) ? $data['pagesize'] : $this->pagesize;
        $data['goods_type'] = isset($data['goods_type']) ? $data['goods_type'] : "100";
        $search = Transit::createTags('search');
        $search->setParam($data);
        $table = Transit::createTags('table');
        $table->setParam($search);
        //店铺id过滤
        $is_admin = Common::getAllowAccess();
        $where    = [];
        if (true === $is_admin) {
            $where['store_id'] = ['=', 'admin'];
        }else{
            $where['store_id'] = $is_admin;
        }
        $where['is_del'] = ['<>', 1];
        $whereTwo        = 1; //内部专属状态
        if (!empty($data['goods_type'])) {
            switch ($data['goods_type']) {
                case 100: //全部
                    break;
                case 1: //已上架
                    $whereTwo .= " and status = 1";
                    break;
                case 2: //推荐商品
                    $whereTwo .= " and referr_status = 1";
                    break;
                case 3: //已下架
                    $whereTwo .= " and status = 2";
                    break;
            }
        }
        //导出订单
        if (!empty($data['daochu'])) {
            $dcw = [];
            if (!empty($data['id'])) {
                $dcw['id'] = ['in', $data['id']];
            }
            $list = db('goods')->where($where)->where($dcw)->where($whereTwo)->order('add_time', 'desc')->select()->toArray();
            return $this->daochu($list);
        }
        $list = $table
                ->query()
                ->where($where)
                ->where($whereTwo)
                ->order('status,upward_time desc')
                ->paginates($pagesize)
                ->each(function ($item) {
                    $goods = db('goods')->where('id', $item['id'])->find();
                    //判断库存是否不足
                    $is_spec_warning = $this->isSpecWarning($item['id']);
                    $item['is_spec_warning'] = !empty($is_spec_warning) ? true : false;
                    $item['status']          = $goods['status'];
                    $item['referr_status']   = $goods['referr_status'];
                    return $item;
                });
        $gm          = new GoodsModel;
        $count1      = $table->query()->where($where)->count();
        $count2      = $table->query()->where($where)->where('status', 1)->count();
        $count3      = $table->query()->where($where)->where('referr_status', 1)->count();
        $count4      = $table->query()->where($where)->where('status', 2)->count();
        $goods_count = [
            'count1' => $count1, //全部商品
            'count2' => $count2, //已上架
            'count3' => $count3, //推荐商品
            'count4' => $count4, //已下架
        ];
        $this->assign('table', $table);
        $list->appends($data);
        $this->assign('searchStr', $search->createHtml());
        $this->assign('list', $list);
        $this->assign('data', $data);
        $this->assign('goods_count', $goods_count);
        $this->assign('page', $list->render());
        return $this->fetch();
    }
    /**
     * 是否规格预警
     */
    public function isSpecWarning($gid)
    {
        try {
            $configs = db('goods_spec_list')->field('id,num,limit')->where(['gid' => $gid])->select()->each(function (&$item, $key) {
                if ($item['num'] < $item['limit']) {
                    return $item['id'];
                } else {
                    return '';
                }
            })->toArray();
            //数组去空；
            $configs = array_filter($configs);
        } catch (\Exception $e) {
            $configs = [];
        }
        return $configs;
    }
    /**
     * 查询当前店铺信息
     */
    private static function getStoreInfo()
    {
        $is_admin = Common::getAllowAccess();
        if (true !== $is_admin) {
            $store_id = $is_admin;
        } else {
            $store_id = 'admin';
        }
        $store = db('store')->where('store_id', $store_id)->find();
        $da    = [];
        if (!empty($store)) {
            $da = $store;
        } else {
            throw new \Exception('未找到' . $store_id . '店铺');
        }
        return $da;
    }
    /**
     * 添加商品
     */
    public function addGoods()
    {
        $data = $this->request->param();
        $add  = Transit::createTags('add');
        if ($this->request->isPost()) {
            checkParam(['goods_name'=>['name'=>'商品名称'],'shop_price'=>['name'=>'售价']],$data);
            $store_info         = self::getStoreInfo();
            $data['add_time']   = time();
            $data['store_id']   = $store_info['store_id'];
            $data['store_name'] = $store_info['store_name'];
            //判断是否开启了审核
            $is_audit = GoodsAuditModel::getAuditIsOpen();
            if ($is_audit == 1) {
                $data['audit_status'] = 1; //开启需要审核
            } else {
                $data['audit_status'] = 2; //跳过审核，直接通过状态
            }
            $res = $add->saveAdd($data);
            if ($res['status'] == true) {
                return $this->success('添加成功');
            } else {
                return $this->error($res['message']);
            }
        }
        $chai = $add->createArrayhtml();
        $this->assign('chai', $chai);
        return $this->fetch('admin_index/addGoods');
    }
    /**
     * 修改商品
     */
    public function editGoods()
    {
        $data = $this->request->param();
        $edit = Transit::createTags('edit');
        //判断是否开启了审核
        $is_audit = GoodsAuditModel::getAuditIsOpen();
        if ($this->request->isPost()) {
            //开启了审核，把商品改为待审核
            if ($is_audit == 1) {
                $data['audit_status'] = 1;
            } else {
                //跳过审核，直接通过状态
                $data['audit_status'] = 2; 
            }
            $data['status'] = 2;
            $data['referr_status'] = 2;
            $res = $edit->saveEdit($data);
            if ($res['status'] == true) {
                if($is_audit == 1){  
                    //添加日志
                    $info = $this->AM->journal('goodsid', $data['id'], 1);
                }else{
                    //添加日志
                    $info = $this->AM->journal('goodsid', $data['id'], 1);   
                    $info = $this->AM->journal('goodsid', $data['id'], 2);   
                }
                //修改库存
                $goods = ( new GoodsModel)->get(['id'=>$data['id']]);
                $count = db('goods_spec_list')->where(['gid'=>$data['id']])->sum('num');
                $goods->save(['inventory'=>$count]);
                return $this->success('修改成功');
            } else {
                return $this->error($res['message']);
            }
        }
        $list = $edit->query()->where('id', $data['id'])->find();
        $chai = $edit->createArrayhtml($list);
        $this->assign('chai', $chai);
        return $this->fetch('admin_index/editGoods');
    }
    /**
     * 商品详情
     */
    public function goodsDetail()
    {
        $data   = $this->request->param();
        $detail = Transit::createTags('detail');
        $list   = $detail->query()->where('id', $data['id'])->find();
        $this->assign('detailStr', $detail->createTableHtml($list));
        $this->specDetail($data['id']);
        
        return $this->fetch('admin_index/goodsDetail');
    }
        //规格列表查看
    public function specDetail($gid=''){
        $search = Transit::createTags('search');
        $table = Transit::createTags('table');  
        $table->setParam($search);
        //搜索结果
        $list   = $table->query()->where('gid',$gid)->select();
        $this->assign('list', $list);
        //配置
        $this->assign('table', $table);
        
    }
    /**
     * 删除商品（软删除）
     */
    public function delGoods()
    {
        $data = $this->request->param();
        if (empty($data['id'])) {
            return $this->error('请先选择要删除的商品！');
        }
        $gm = new GoodsModel;
        $res = $gm->unfinishedOrderNum($data['id']);
        if ($res['order_count'] != 0) {
            return $this->error('该商品下有' . $res['order_count'] . '个未完成订单，不可删除');
        }
        if (is_array($data['id'])) {
            $gm->save(['is_del' => 1], ['id' => ['in', $data['id']]]);
        } else {
            $gm->save(['is_del' => 1], ['id' => ['=', $data['id']]]);
        }
        return $this->success('删除成功');
    }
    /**
     * 批量选择
     */
    public function pilaing()
    {
        $data = $this->request->param();
        if (empty($data['id'])) {
            $this->error('请选择需要操作的数据');
        }
        $gm  = new GoodsModel;
        $id  = $data['id'];
        $upd = [];
        switch ($data['type']) {
            case 1: //批量下架
                $upd['status']    = 2;
                $upd['referr_status'] = 2;  //下架取消推荐
                $upd['dowm_time'] = time(); //下架时间
                break;
            case 2: //批量上架
                $upd['status']      = 1;
                $upd['upward_time'] = time(); //上架时间
                break;
            case 3:
                $upd['referr_status'] = 2;  //不推荐
                break;
            case 4:
                $upd['referr_status'] = 1;  //推荐
                break;
            case 5:
                $res = $gm->unfinishedOrderNum($data['id']);
                if ($res['order_count'] != 0) {
                    return $this->error('所选商品中有' . $res['order_count'] . '个未完成订单，不可删除');
                }
                $upd['is_del'] = 1;
                break;
        }
        $gm->where('id', 'in', $id)->update($upd);
        $this->success('操作成功');
    }
    /**
     * 导出选项
     */
    protected function exportOption()
    {
        $option = [[
            'name'  => '商品id',
            'field' => 'id',
            'type'  => 'text',
        ], [
            'name'  => '缩略图',
            'field' => 'goods_img',
            'type'  => 'image',
        ], [
            'name'  => '简介',
            'field' => 'goods_brief',
            'type'  => 'text',
        ], [
            'name'  => '价格',
            'field' => 'shop_price',
            'type'  => 'text',
        ], [
            'name'  => '原价',
            'field' => 'market_price',
            'type'  => 'text',
        ], [
            'name'  => '销量',
            'field' => 'sell_num',
            'type'  => 'text',
        ], [
            'name'  => '状态(上架/下架)',
            'field' => 'status',
            'type'  => 'text',
        ], [
            'name'  => '添加时间',
            'field' => 'add_time',
            'type'  => 'text',
        ], [
            'name'  => '库存',
            'field' => 'inventory',
            'type'  => 'text',
        ], [
            'name'  => '店铺id',
            'field' => 'store_id',
            'type'  => 'text',
        ], [
            'name'  => '店铺名称',
            'field' => 'store_name',
            'type'  => 'text',
        ], [
            'name'  => '审核状态',
            'field' => 'audit_status',
            'type'  => 'text',
        ], [
            'name'  => '是否推荐',
            'field' => 'referr_status',
            'type'  => 'text',
        ], [
            'name'  => '上架时间',
            'field' => 'upward_time',
            'type'  => 'text',
        ], [
            'name'  => '下架时间',
            'field' => 'dowm_time',
            'type'  => 'text',
        ]];
        return $option;
    }
    /**
     * 处理导出数据
     */
    private function transdata(&$value)
    {
        $value['status']   = ($value['status'] == 1) ? '上架' : '下架';
        $value['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
        switch ($value['audit_status']) {
            case '1':
                $value['audit_status'] = '审核中';
                break;
            case '2':
                $value['audit_status'] = '通过';
                break;
            case '3':
                $value['audit_status'] = '被驳回';
                break;
            default:
                $value['audit_status'] = '无';
                break;
        }
        $value['referr_status'] = ($value['referr_status'] == 1) ? '推荐' : '非推荐';
        $value['upward_time']   = $value['upward_time'] ? date('Y-m-d H:i:s', $value['upward_time']) : '';
        $value['dowm_time']     = $value['dowm_time'] ? date('Y-m-d H:i:s', $value['dowm_time']) : '';
    }
    /**
     * 导出商品
     */
    public function daochu($list)
    {
        $export_option = $this->exportOption();
        $option        = array_column($export_option, 'field', 'name');
        $name          = array_keys($option);
        $field         = array_values($option);
        include VENDOR_PATH . 'phpoffice/phpexcel/Classes/PHPExcel.php';
        $PHPExcel = new \PHPExcel();
        $PHPExcel
            ->getProperties() //获得文件属性对象，给下文提供设置资源
            ->setCreator("MaartenBalliauw") //设置文件的创建者
            ->setLastModifiedBy("MaartenBalliauw") //设置最后修改者
            ->setTitle("Office2007 XLSX Test Document") //设置标题
            ->setSubject("Office2007 XLSX Test Document") //设置主题
            ->setDescription("Test document for Office2007 XLSX, generated using PHP classes.") //设置备注
            ->setKeywords("office 2007 openxmlphp") //设置标记
            ->setCategory("Test resultfile"); //设置类别
        $objActSheet = $PHPExcel->getActiveSheet();
        $phpcc       = $PHPExcel->setActiveSheetIndex(0);
        //表头
        $k = 'A';
        foreach ($name as $kname => $vname) {
            $phpcc->setCellValue($k . '1', $vname);
            $k++;
        }
        //表数据
        $i = 2;
        foreach ($list as $key => $value) {
            $this->transdata($value);
            $a = 'A';
            foreach ($field as $k2 => $v2) {
                if (empty($value[$v2])) {
                    $phpcc->setCellValue($a . $i, $value[$v2] . ' ');
                } else {
                    switch ($export_option[$k2]['type']) {
                        //导出类型处理
                        case 'text':
                            $phpcc->setCellValue($a . $i, $value[$v2] . ' ');
                            break;
                        case 'image':
                            $phpcc->setCellValue($a . $i, $value[$v2] . ' ');
                            break;
                            $objDrawing = new \PHPExcel_Worksheet_Drawing(); //必须每次重新实例化
                            $objDrawing->setPath('.' . $value[$v2]); //这里是相对路径
                            $objDrawing->setHeight(80); //照片高度
                            $objDrawing->setWidth(80);
                            $objDrawing->setCoordinates($a . $i);
                            // 图片偏移距离
                            $objDrawing->setOffsetX(12);
                            $objDrawing->setOffsetY(12);
                            $objDrawing->setWorksheet($PHPExcel->getActiveSheet());
                            //设置列宽
                            $PHPExcel->getActiveSheet()->getColumnDimension($a)->setWidth(14);
                            //设置行高
                            $PHPExcel->getActiveSheet()->getRowDimension($i)->setRowHeight(80);
                            break;
                        default:
                            $phpcc->setCellValue($a . $i, $value[$v2] . ' ');
                            break;
                    }
                }
                $a++;
            }
            $i++;
        }
        $time = date('m月d日', time());
        $objActSheet->setTitle($time . '商品信息'); //sheet标题
        //生成的文件名
        $filename = $time . "商品信息" . ".xlsx";
        //生成2007excel格式的xlsx文件
        header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition:attachment;filename="' . $filename . '"');
        header('Cache-Control:max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        $xlsData = ob_get_contents();
        ob_end_clean();
        $data = ['filename' => $filename, 'file' => "data:application/vnd.ms-excel;base64," . base64_encode($xlsData)];
        return $this->success('下载成功', '', $data);
    }
}
